package v1

import (
    "net/http"
    "log"
    "fmt"
    "strconv"
    "github.com/gin-gonic/gin"
     ."main/models"
)

func IndexApi(c *gin.Context) {
    c.String(http.StatusOK, "It works")
}

func AddPersonApi(c *gin.Context) {
    firstName := c.Request.FormValue("first_name")
    lastName := c.Request.FormValue("last_name")
    p := Person{FirstName: firstName, LastName: lastName}
    log.Println(p)
    ra, err := p.AddPerson()
    if err != nil {
        log.Fatalln(err)
    }
    msg := fmt.Sprintf("insert successful %d", ra)
    c.JSON(http.StatusOK, gin.H{
        "code": 200,
        "msg": msg,
    })
}

func GetPersonsApi(c *gin.Context) {

    var p Person
    persons, err := p.GetPersons()
    if err != nil {
        log.Fatalln(err)
    }

    c.JSON(http.StatusOK, gin.H{
        "msg": persons,
    })

}

func GetPersonApi(c *gin.Context) {
    cid := c.Param("id")
    claims := c.MustGet("claims")

    log.Println("+%v",claims)

    id, err := strconv.Atoi(cid)
    if err != nil {
        log.Fatalln(err)
    }
    p := Person{Id: id}
    log.Println("v",p)
    person, err := p.GetPerson()
    if err != nil {
        log.Fatalln(err)
    }

    c.JSON(http.StatusOK, gin.H{
        "msg": person,
    })

}

func ModPersonApi(c *gin.Context) {
    cid := c.Param("id")
    firstName :=  c.Request.FormValue("first_name")
    lastName :=  c.Request.FormValue("last_name")

    id, err := strconv.Atoi(cid)
    if err != nil {
        log.Fatalln(err)
    }
    p := Person{Id: id,FirstName:firstName,LastName:lastName}
    err = c.Bind(&p)
    if err != nil {
        log.Fatalln(err)
    }
    err = p.ModPerson()
    if err != nil {
        log.Fatalln(err)
    }
    msg := fmt.Sprintf("Update person %d", p.Id)
    c.JSON(http.StatusOK, gin.H{
        "msg": msg,
    })
}

func DelPersonApi(c *gin.Context) {
    cid := c.Param("id")
    id, err := strconv.Atoi(cid)
    if err != nil {
        log.Fatalln(err)
    }
    p := Person{Id: id}
    err = p.DelPerson()
    if err != nil {
        log.Fatalln(err)
    }
    msg := fmt.Sprintf("Delete person %d", id)
    c.JSON(http.StatusOK, gin.H{
        "msg": msg,
    })
}